package login
{
	import application.Application;
	import application.ApplicationConstants;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	import utils.http.FailureResponse;
	import utils.http.HttpConnector;
	import utils.http.SuccessResponse;
	import utils.http.builder.HttpConnectorBuilder;
	
	public class LoginController
	{
		
		public function LoginController()
		{
		}

		public function buscarUsuariosFromEmpresa(codigoEmpresa:String, listener:Function):void {
			var conn:HttpConnector = new HttpConnector();
			conn.url = ApplicationConstants.getUrl(ApplicationConstants.AUTENTICACAO_USUARIOS_BY_EMPRESA_RESOURCE, ("codigo=" + codigoEmpresa));
			conn.method = "GET";
			conn.sendToken = false;
			conn.verifyToken = false;
			
			conn.onSuccess(function(response:SuccessResponse):void {
				var xml:XML = new XML(response.content);
				
				var usuariosXML:XMLList = xml.usuario;
				var usuarios:ArrayCollection = new ArrayCollection();
							
				for (var i:int = 0; i < usuariosXML.length(); i++) {
					usuarios.addItem(new Usuario(usuariosXML.nome[i], usuariosXML.login[i], usuariosXML.codigoEmpresa[i]));
				}
								
				listener.apply(null, new Array(usuarios));
			});	
			
			conn.onFailure(function(response:FailureResponse):void {
				Alert.show(response.responseMessage);
			});
			
			conn.connect();
		}

		public function autenticarUsuario(usuario:Usuario, senha:String, listener:Function):void {
			var url:String = ApplicationConstants.getUrl(ApplicationConstants.EFETUAR_LOGIN_RESOURCE, null);

			var conn:HttpConnectorBuilder = new HttpConnectorBuilder(url);
			conn.methodPost("login=" + usuario.login + "&senha=" + senha);
			conn.secure(false);
			
			conn.onSuccess(function(response:SuccessResponse):void {
				var xml:XML = new XML(response.content);
				
				var usuarioLogado:Usuario = new Usuario(xml.nome, xml.login, xml.codigoEmpresa);
				
				Application.get().addAttribute(ApplicationConstants.USUARIO_LOGADO_ATTR, usuarioLogado);
				
				listener.apply(null, new Array(usuarioLogado));
			});
			
			conn.onFailure(function(response:FailureResponse):void {
				Alert.show(response.responseMessage);
			});
			
			conn.connect();
		}
	}
}